<?php
/**
 * Created by PhpStorm.
 * User: M2
 * Date: 13-11-27
 * Time: 下午6:31
 */
class YlPageSqlContentsTaglib {
    private $nowPage = 1;
    private $count = 0;
    private $pagesize = 20;
    private $totalPage = 0;
    private $_dbPrefix = 'yl_';
    
    public function __construct() {
        C(include SITE_PATH.'/extends/taglib/tagarr.php');
        $dbPrefix = C('db_prefix');
        !empty($dbPrefix) && $this->_dbPrefix = $dbPrefix;
    }
    public function parse($content,$cateid,$siteid,$channels,$templatePath,$domain,$channel, $catenaming) {
        if (stripos($content, 'yl:pagesqlContents') !== false) {
            $matches = preg_parse($content, 'yl:pagesqlContents');
            $pagesize = getParseOneAttr($matches[0], 'pagesize');
            $scope = getParseOneAttr($matches[0], 'scope');
            $order = getParseOneAttr($matches[0], 'order');

            $this->pagesize = $pagesize?$pagesize:$this->pagesize;//获取并设置每页显示多少条
            $contentText = getParseContentText($matches[0], 'yl:pagesqlContents');
            $matchQueryString = preg_parse($contentText, 'yl:queryString');
            $sql = getParseContentText($matchQueryString[0], 'yl:queryString');

            if (!empty($sql)) {
                $sqls = 'select count(1) as count from('.trim($sql).') P';
                $res = M()->query($sqls);
                $this->count = $res[0]['count'];
                $result = M()->query(trim($sql));
            } else {
                //update next 2013-12-12 调整这里的位置,有sql时，这些都不用查询
                $data['siteid'] = $siteid;
                $data['cid'] = $cateid;
                if (strtolower($scope) === 'all') {
                    //add next 2013-12-12  增加得到子栏目列表的缓存,过期300秒
                    if (($gcate = S('cache_childcate_'.$cateid)) === false) {
                        $gcate = D('Category')->getChildCate($cateid);
                        S('cache_childcate_'.$cateid, $gcate,300);
                    }
                    $data = 'siteid='.$siteid.' and FIND_IN_SET( cid, "'.$gcate.'" )';
                }
                $order = $order ? $order.' desc' : 'updatetime desc';

                $this->count = M('cms_article')->where($data)->count(); //统计当前栏目下的所有内容总数

                $result = M('cms_article')
                    ->field('(case when url <> "" then url else
                        (concat("'.$domain.'","/",replace(replace((select (case when B.artnaming <> ""
                		 then B.artnaming else ("'.$channel['artnaming'].'") end) from '.$this->_dbPrefix.'cms_category B where B.id=cid),"{cateid}",
                        cid),"{contentid}",id))) end) as url,
                        replace(imageurl,"@","'.$domain.'") as imageurl,replace(big_imageurl,"@","'.$domain.'") as big_imageurl,title,summary,group_name_collection,
                        subtitle,author,updatetime,inputtime,tags,source,content,readpoint,keywords,cid,id,siteid,description,create_uid,create_uname,update_uid,update_uname,fileurl')
                    ->where($data)->order($order)->select(); //获取内容列表
            }

            $this->totalPage = ceil($this->count/$this->pagesize); //总页数
            if($this->nowPage >= $this->totalPage) $this->nowPage = $this->totalPage; //如果当前页大于总页数，就让当前页=总页数
            if($this->nowPage<=1) $this->nowPage = 1; //如果当前页小于1，当前页=1

            for($i=1;$i<=$this->totalPage;$i++) {
                $this->nowPage = $i;
                $start = $this->pagesize * ($this->nowPage -1); //获取起始页
                $list = array_slice($result, $start, $this->pagesize);
                $parseStr = '';
                $pageSqlContentsText = getParseContentText($matches[0], 'yl:pagesqlContents');
                $pageSqlContentsText = str_replace($matchQueryString[0], '', $pageSqlContentsText);
                if(!empty($list)) {
                    foreach ($list as $k => $v) {
                        //update next 2013-12-12 简化替换操作
                        $text = taglib(C('yl:if'))->parse($pageSqlContentsText, $v);
                        $text = taglib(C('yl:sqlcontent'))->parse($text,$v);
                        $text = taglib(C('yl:a'))->parse($text,'',$v,'1',$domain,$channel);
                        $text = taglib(C('yl:content'))->parse($text,$v,$domain);
                        $text = taglib(C('yl:image'))->parse($text,$v);
                        $text = taglib(C('yl:count'))->parse($text,$v);

                        if(strpos($text,'{') && strpos($text,'}')) {
                            preg_match_all('/\{Content.(.*?)\}/eis',$text,$out);
                            for ($j=0; $j< count($out[0]); $j++) {
                                $text = str_ireplace($out[0][$j],$v[$out[1][$j]],$text);
                            }
                            preg_match_all('/\{Sql.(.*?)\}/eis',$text,$out);
                            for ($j=0; $j< count($out[1]); $j++) {
                                $text = str_ireplace($out[0][$j],$v[$out[1][$j]],$text);
                            }
                        }
                        $parseStr .= $text;
                    }
                } else {
                    $parseStr = '';
                }
                $pageSqlContent = str_replace($matches[0], $parseStr, $content);
                $matchItems = preg_parse($pageSqlContent, 'yl:pageItems');
                foreach($matchItems as $fp) {
                    $text = getParseContentText($fp, 'yl:pageItems');
                    $matchesPageItem = preg_parse($text, 'yl:pageItem');
                    foreach($matchesPageItem as $epageitem) {
                        $text = taglib(C('yl:pageitem'))->parse($epageitem,$channels,$this->count,$this->pagesize,$this->nowPage,$domain);
                        $pageSqlContent = str_replace($epageitem, $text, $pageSqlContent);
                    }
                    $qtext = getParseContentText($fp, 'yl:pageItems');
                    $pageSqlContent = str_replace($fp, $qtext, $pageSqlContent);
                }
                $arr = explode('.',$catenaming);
                if($this->nowPage == 1)
                    $contents['catenaming'] = $arr[0].'.'.$arr[1];
                else
                    $contents['catenaming'] = $arr[0].'_'.$this->nowPage.'.'.$arr[1];

                if(dirname($templatePath.$contents['catenaming']))
                    mk_dir(dirname($templatePath.$contents['catenaming']));

                $path = $templatePath.$contents['catenaming'];
                $pageSqlContent = taglib('YlA')->parse($pageSqlContent,$siteid,$channels,'1', $domain, $channel);
                $pageSqlContent = taglib('YlImage')->parse($pageSqlContent, $channels);
                $pageSqlContent = taglib('YlChannel')->parse($pageSqlContent,$channels, $siteid, $domain, $channel);
                file_put_contents($path,$pageSqlContent);
            }
            return '';
        }
        return $content;
    }
}